// pages/search/search.js
Page({
  data: {
    value: '',
    history: [],
    showSearch: true,
    showProductions: false,
    tabActives: ['active', '', ''],
    saleSortActives: ['', ''],
    priceSortActives: ['', '']
  },
  onClick(_e) {
    this.setData({
      showSearch: true,
      showProductions: false
    })
  },
  onChange(e) {
    this.setData({
      value: e.detail,
    });
  },
  onLoad() {
    wx.getStorage({
      'key': 'history'
    }).then(r => {
      this.setData({
        history: r.data
      })
    }).catch(_e => { /* nothing */ })
  },
  onSearch() {
    const v = this.data.value
    if (v) {
      this.setData({
        showSearch: false,
        showProductions: true
      })
      wx.getStorage({
        'key': 'history'
      }).then(res => {
        const vs = res.data
        vs.push(v)
        const vset = Array.from(new Set(vs))
        wx.setStorage({
          'key': 'history',
          'data': vset
        })
        this.setData({
          history: vset
        })
      }).catch(_e => {
        const vs = Array.of(v)
        wx.setStorage({
          'key': 'history',
          'data': vs
        })
        this.setData({
          history: vs
        })
      })
    }
  },
  clearHistory() {
    wx.removeStorage({
      key: 'history'
    }).then(_r => {
      this.setData({
        history: []
      })
    })
  },
  quickSearch(e) {
    const value = e.target.dataset.text
    this.setData({ value })
    this.onSearch()
  },
  tabClick(e) {
    const index = e.currentTarget.dataset.index
    if (index == 1) {
      this.setData({
        tabActives: ['', 'active', ''],
        priceSortActives: ['', '']
      })
      if (this.data.saleSortActives[0] === 'active') {
        this.setData({
          saleSortActives: ['', 'active']
        })
      } else {
        this.setData({
          saleSortActives: ['active', '']
        })
      }
    } else if (index == 2) {
      this.setData({
        tabActives: ['', '', 'active'],
        saleSortActives: ['', '']
      })
      if (this.data.priceSortActives[0] === 'active') {
        this.setData({
          priceSortActives: ['', 'active']
        })
      } else {
        this.setData({
          priceSortActives: ['active', '']
        })
      }
    } else {
      this.setData({
        tabActives: ['active', '', ''],
        saleSortActives: ['', ''],
        priceSortActives: ['', '', '']
      })
    }
  }
})
